from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection

from rest_framework.response import Response

from rest_framework.views import APIView

from goods.models import SKU

from orders.serializers import CartSKUSerializer,PlaceOrderSerializer,OrderSerializer


from rest_framework.permissions import IsAuthenticated


class PlaceOrderAPIView(APIView):


    permission_classes = [IsAuthenticated]

    def get(self,request):

        user=request.user

        redis_conn=get_redis_connection('cart')

        redis_id_counts=redis_conn.hgetall('cart_%s'%user.id)

        redis_selected_ids=redis_conn.smembers('cart_selected_%s'%user.id)

        redis_selected_cart={}

        for sku_id in redis_selected_ids:
            redis_selected_cart[int(sku_id)]=int(redis_id_counts[sku_id])

        ids=redis_selected_cart.keys()

        skus=SKU.objects.filter(pk__in=ids)

        for sku in skus:
            sku.count=redis_selected_cart[sku.id]


        from decimal import Decimal

        freight=Decimal('10.00')

        serializer=PlaceOrderSerializer(
            {
                'freight':freight,
                'skus':skus
            }
        )
        return Response(serializer.data)


class OrderAPIView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self,request):

        data=request.data

        serializer=OrderSerializer(data=data,context={'request':request})
        serializer.is_valid()

        serializer.save()

        return Response(serializer.data)

